//
//  KABHpEditInforVC.m
//  kabu
//
//  Created by XiangDongMBP on 2017/2/17.
//  Copyright © 2017年 East. All rights reserved.
//

#import "KABHpEditInforVC.h"
#import "KABHpEditInfoTCell.h"
#import "KABModel.h"
#import "ApiManager.h"
#import "XDAFNetworking.h"
#import "GlobalHeader.h"
#import "KABHpEditNameVC.h"
#import "MBProgressHUD+XDPrompt.h"
#import "KABHpEditSignVC.h"
#import "XDPickerCityView.h"

@interface KABHpEditInforVC ()<UITableViewDelegate, UITableViewDataSource, XDPickerCityViewDelegate>

@property (weak,     nonatomic) IBOutlet UITableView *tableView;
@property (strong,   nonatomic) NSArray<NSDictionary *> * infoArray;
@property (readonly, nonatomic) NSArray<NSString *> *userInfoArray;

@end

static NSString *const kReuseCellId = @"KABHpEditInfoTCell";

@implementation KABHpEditInforVC

#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initNavigationBar];
    [self initSubViews];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self refreshWholeView];
}

- (void)initNavigationBar {
    self.navigationItem.title = @"个人信息";
}

- (void)initSubViews {
    UINib *nib = [UINib nibWithNibName:kReuseCellId bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:kReuseCellId];
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 44.0;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.infoArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    KABHpEditInfoTCell *cell = [tableView dequeueReusableCellWithIdentifier:kReuseCellId forIndexPath:indexPath];
    cell.titleLabel.text = self.infoArray[indexPath.row][@"title"];
//    cell.desLabel.text = self.infoArray[indexPath.row][@"content"];
    cell.desLabel.text = self.userInfoArray[indexPath.row];
    return cell;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 5.9;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.1;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.row == 0) {
        [self modifyNickName];
    } else if (indexPath.row == 1) {
        [self modifySex];
    } else if (indexPath.row == 2) {
        [self modifyAddress];
    } else if (indexPath.row == 3) {
        [self modifyAutograph];
    }
}

#pragma mark - XDPickerCityViewDelegate
- (void)xDPickerCityView:(XDPickerCityView *)XDFilterView province:(NSString *)province city:(NSString *)city {
    [self requestEditUserInfoWithNickName:nil sex:-1 province:province city:city sign:nil];
}

#pragma mark - event response

#pragma mark - private methods
- (void)modifyNickName {
    KABHpEditNameVC *vc = [[KABHpEditNameVC alloc] init];
    [self showViewController:vc sender:nil];
}
- (void)modifySex {
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"女" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self requestEditUserInfoWithNickName:nil sex:0 province:nil city:nil sign:nil];
    }]];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"男" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self requestEditUserInfoWithNickName:nil sex:1 province:nil city:nil sign:nil];
    }]];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:alertVC animated:YES completion:nil];
}
- (void)modifyAddress {
    XDPickerCityView *pickerView = [[XDPickerCityView alloc] init];
    pickerView.delegate = self;
    [pickerView showInView:self.view];
}
- (void)modifyAutograph {
    KABHpEditSignVC *vc = [[KABHpEditSignVC alloc] init];
    [self showViewController:vc sender:nil];
}

- (void)refreshWholeView {
    // 尾部加载更多的显示
    //    if (self.model.taskList.count >= self.model.totalCount) {
    //        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    //    } else {
    //        [self.tableView.mj_footer resetNoMoreData];
    //    }
    
    [self.tableView reloadData];
}

#pragma mark - network request
// sex = -1 表示不修改sex
- (void)requestEditUserInfoWithNickName:(NSString *)nickName sex:(NSInteger)sex province:(NSString *)province city:(NSString *)city sign:(NSString *)sign {
    // 发布Cos需要登录
    if (![KABModel sharedInstance].isLogin) {
        [[NSNotificationCenter defaultCenter] postNotificationName:KABGlobalNotiUserTokenInvalid object:nil];
        return;
    }
    
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];

    NSMutableDictionary *pars = [NSMutableDictionary dictionary];
    [pars setObject:@([KABModel sharedInstance].userInfo.uid) forKey:@"user_id"];
    [pars setObject:[KABModel sharedInstance].userInfo.access_token forKey:@"access_token"];
    [pars setObject:(nickName ? nickName : [KABModel sharedInstance].userInfo.nick_name) forKey:@"nick_name"];
    [pars setObject:@((sex != -1) ? sex : [KABModel sharedInstance].userInfo.sex ) forKey:@"sex"];
    if (province) {
        [pars setObject:province forKey:@"province"];
    }
    if (city) {
        [pars setObject:city forKey:@"city"];
    }
    if (sign) {
        [pars setObject:sign  forKey:@"sign"];
    }
    
    [[XDAFNetworking sharedInstance] PUT:[ApiManager apiModifyMyInfo] parameters:pars success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"修改个人信息成功：%@", responseObject);
        [hud hideAnimated:YES];
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            [[KABModel sharedInstance] updateNickName:pars[@"nick_name"]
                                                  sex:[pars[@"sex"] integerValue]
                                             province:pars[@"province"]
                                                 city:pars[@"city"]
                                                 sign:pars[@"sign"]];
            [self refreshWholeView];
        } else {
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"修改个人信息失败：%@", error);
        [hud hideAnimated:NO];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}

#pragma mark - getters and setters
- (NSArray<NSDictionary *> *)infoArray {
    if (!_infoArray) {
        _infoArray = @[@{@"title" : @"昵称", @"content" : @"马飞"},
                       @{@"title" : @"性别", @"content" : @"男"},
                       @{@"title" : @"地区", @"content" : @"广东 深圳"},
                       @{@"title" : @"简介", @"content" : @"人生如棋，落子无悔。"}];
    }
    return _infoArray;
}

- (NSArray<NSString *> *)userInfoArray {
    return  @[[KABModel sharedInstance].userInfo.nick_name,
              [KABModel sharedInstance].userInfo.sexStr,
              [KABModel sharedInstance].userInfo.areaStr,
              [KABModel sharedInstance].userInfo.sign];
}

@end
